package net.roobook.cms.modules.admin.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.github.pagehelper.PageInfo;
import net.roobook.cms.common.annotation.Log;
import net.roobook.cms.common.annotation.Log.OperatorType;
import net.roobook.cms.common.entity.SearchEntity;
import net.roobook.cms.common.entity.StateCodeEnum;
import net.roobook.cms.common.exception.CmsException;
import net.roobook.cms.common.web.BaseController;
import net.roobook.cms.modules.admin.entity.User;
import net.roobook.cms.modules.admin.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

/**
 * @author cos
 * @email 327878610@qq.com
 * @link https://roobook.net
 * @Description 用户管理controller
 * @date 2023/9/24 21:30
 **/
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    /**
     * 分页
     * @param model
     * @param entity
     * @return
     */
    @Log(operType = OperatorType.PAGE, module = "用户管理", content = "用户分页列表")
    @RequestMapping({"","list"})
    public ModelAndView list(Model model, SearchEntity entity) {
        ModelAndView mv = new ModelAndView();
        PageInfo<User> page = userService.queryListByPage(entity);
        mv.addObject("page", page);
        mv.setViewName("admin/user/list");
        return mv;
    }
    @Log(operType = OperatorType.OTHER, module = "用户管理", content = "添加用户页面")
    @RequestMapping("toAdd")
    public ModelAndView toAdd() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("admin/user/add");
        return mv;
    }

    /**
     *
     * @param user
     * @return
     * @throws CmsException
     * @throws UnsupportedEncodingException
     */
    @Log(operType = OperatorType.INSERT, module = "用户管理", content = "添加用户")
    @RequestMapping("add")
    public String add(User user) throws CmsException, UnsupportedEncodingException {
        User temp = userService.getByUserName(user.getUsername());
        if(temp != null) {
            throw new CmsException(
                    StateCodeEnum.USERNAME_EXIST_EXCEPTION.getCode(),
                    StateCodeEnum.USERNAME_EXIST_EXCEPTION.getDescription(),
                    "输入的用户名已经存在，请输入其它用户名再次尝试。");
        }
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        if(StrUtil.isNotBlank(user.getPassword())) {
            Digester md5 = new Digester(DigestAlgorithm.MD5);
            String digestHex = md5.digestHex(salt+user.getPassword());
            user.setPassword(digestHex);
        }
        user.setId(IdUtil.getSnowflakeNextIdStr());
        user.setCreateBy(getUserId());
        user.setCreateTime(new Date());
        try {
            int i = userService.add(user);
        } catch (Exception e) {
            throw new CmsException(
                    StateCodeEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(),
                    StateCodeEnum.HTTP_INTERNAL_SERVER_ERROR.getDescription(),
                    e.getMessage());
        }
        return "redirect:/admin/user/list";
    }

    @Log(operType = OperatorType.OTHER, module = "用户管理", content = "修改用户页面")
    @RequestMapping("toEdit")
    public ModelAndView toEdit(String id) {
        ModelAndView mv = new ModelAndView();
        User user = userService.queryEntityById(id);
        mv.addObject("user", user);
        mv.setViewName("admin/user/edit");
        return mv;
    }

    /**
     * 修改用户
     * @param user
     * @return
     * @throws CmsException
     */
    @Log(operType = OperatorType.UPDATE, module = "用户管理", content = "修改用户")
    @RequestMapping("update")
    public String update(User user) throws CmsException {
        user.setUpdateBy(getUserId());
        user.setUpdateTime(new Date());
        try {
            int i = userService.update(user);
        } catch (Exception e) {
            throw new CmsException(
                    StateCodeEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(),
                    StateCodeEnum.HTTP_INTERNAL_SERVER_ERROR.getDescription(),
                    e.getMessage());
        }
        return "redirect:/admin/user/list";
    }

    /**
     * 删除
     */
    @Log(operType = OperatorType.DELETE, module = "用户管理", content = "删除用户")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(Model model, String id) {
        userService.delete(id);
        return "redirect:/admin/user/list";
    }
}
